// src/api.js
import axios from 'axios';
import { Loading} from 'element-ui'
import {Message} from "element-ui";
import setstorage from "@/utils/setstorage";
 // 假设有一个自定义的错误提示函数
let loadingObj = null
const api = axios.create({// 47.115.32.210
    baseURL:'http://localhost:8089/api', //   192.168.193.104: 47.115.32.210
    timeout: 50000,
});

// 添加请求拦截器
api.interceptors.request.use(config => {

    let passToken =  localStorage.getItem('token')
    if(passToken !== null){
        passToken =JSON.parse(passToken).value
        console.log("passToken:" + passToken)
    }

    loadingObj =  Loading.service({  //增加loading页面效果
        lock:true,  //是否显示动画
        text:'loading',
        background:'rgba(0,0,0,0,7)'
    })

    const token = passToken

    if (token) {
       // 将 token 放到请求头中
        config.headers.Authorization = `${token}`;
    }
    return config;
}, error => {

    return Promise.reject(error);
});

// 添加响应拦截器
api.interceptors.response.use(response => {
        loadingObj.close()
        let resData =  response.data

     if(resData.code===200|| resData){
        return resData
     }else if (resData.code === 901){

         console.log('请求超时')
         return null;

         // return Promise.reject({showError:true,msg:"请求超时"})
     }else{
         console.log('网络异常')
         return null;
         // return Promise.reject({showError:true,msg:"网络异常"})
     }


    },
    error => {
        loadingObj.close()
        const { status, data } = error.response || {};
        if (status === 401) {
            // 处理未授权的情况，比如跳转到登录页
        }
        // showError(data.message || '网络错误，请稍后再试！');
        return Promise.reject(error);
    });

// 封装GET请求
export  function get(url, params = {}) {
     return  api.get(url, {params})

}

// 封装POST请求
export  function post(url, data = {}) {
      return  api.post(url, data)


}

